package com.agileai.portal.portlets.iframe;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.HashMap;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import javax.portlet.PortletModeException;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequest;
import javax.portlet.ProcessAction;
import javax.portlet.ReadOnlyException;
import javax.portlet.RenderMode;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.portlet.ValidatorException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.codehaus.jettison.json.JSONObject;
import org.mvel2.templates.TemplateRuntime;

import com.agileai.portal.driver.GenericPotboyPortlet;
import com.agileai.portal.driver.Resource;
import com.agileai.portal.driver.common.PortletRequestHelper;
import com.agileai.portal.driver.common.PortletVariableHelper;
import com.agileai.portal.driver.common.PreferenceException;
import com.agileai.portal.driver.common.PreferencesHelper;
import com.agileai.portal.driver.common.PreferencesWrapper;
import com.agileai.portal.driver.model.MenuBar;
import com.agileai.portal.driver.model.Theme;
import com.agileai.util.StringUtil;

public class DynamicIframePortlet extends GenericPotboyPortlet {
	private static final String DynamicRetrieve = "DynamicRetrieve";
	
	@SuppressWarnings("rawtypes")
	@RenderMode(name = "view")
	public void view(RenderRequest request, RenderResponse response)
			throws PortletException, IOException {
		PortletPreferences preferences =  PreferencesHelper.getPublicPreference(request);
		String iframeHeight = preferences.getValue("iframeHeight", null);
		String iframeURL = preferences.getValue("iframeURL", null);
		
		if (!StringUtil.isNullOrEmpty(iframeHeight) && !StringUtil.isNullOrEmpty(iframeURL) 
				){
			request.setAttribute("isSetting", "Y");
		}else{
			request.setAttribute("isSetting", "N");
		}
		
		String isSetting = (String)request.getAttribute("isSetting");
		if ("Y".equals(isSetting)){
			
			if (iframeHeight.indexOf(Theme.ThemeBodyHeight) > -1){
				String template = iframeHeight;
				HashMap vars = this.buildVarMap(request);
				iframeHeight = String.valueOf(TemplateRuntime.eval(template, vars));
			}
			request.setAttribute("iframeHeight", iframeHeight);
			request.setAttribute("portletId", request.getWindowID());
			
			if (DynamicRetrieve.equals(iframeURL)){
				HttpServletRequest httpServletRequest = PortletRequestHelper.getRequestContext(request).getServletRequest();
				String currentVirtualMenuId = httpServletRequest.getParameter(MenuBar.VIRTUAL_MENU_KEY);
				HttpSession session = PortletRequestHelper.getPortalHttpSession(request);
				HashMap<String,JSONObject> jsonMap = MenuBar.getMenuJSONObjectMap(session);
				JSONObject jsonObject = jsonMap.get(currentVirtualMenuId);
				try {
					String url = jsonObject.getString("url");
					request.setAttribute("iframeURL", url);
				}catch(Exception e){
					e.printStackTrace();
				}
			}			
		}
		super.doView(request, response);
	}

	@SuppressWarnings({"rawtypes", "unchecked" })
	private HashMap buildVarMap(PortletRequest request){
		HashMap result = new HashMap();
		HttpSession portalSession = PortletRequestHelper.getPortalHttpSession(request);
		Theme theme = (Theme)portalSession.getAttribute(Theme.class.getName());
		String height = (String)portalSession.getAttribute(Theme.WindowScreenHeight);
		String outherHeight = theme.getOuterHeight();
		String themeBodyHeight = String.valueOf(Integer.parseInt(height)- Integer.parseInt(outherHeight));
		result.put(Theme.ThemeBodyHeight, themeBodyHeight);
		return result;
	}
	
	@RenderMode(name = "edit")
	public void edit(RenderRequest request, RenderResponse response)
			throws PortletException, IOException {
		PortletPreferences preferences = PreferencesHelper.getPublicPreference(request);
		String iframeHeight = preferences.getValue("iframeHeight", null);
		String iframeURL = preferences.getValue("iframeURL", null);
		String defaultVariableValues = preferences.getValue("defaultVariableValues", "");
		
		request.setAttribute("iframeHeight", iframeHeight);
		request.setAttribute("iframeURL", iframeURL);
		request.setAttribute("defaultVariableValues", defaultVariableValues);
		
		super.doEdit(request, response);
	}
	@ProcessAction(name = "saveConfig")
	public void saveConfig(ActionRequest request, ActionResponse response)
			throws ReadOnlyException, PortletModeException, ValidatorException,
			IOException, PreferenceException {
		String iframeHeight = request.getParameter("iframeHeight");
		String iframeURL = request.getParameter("iframeURL");
		String defaultVariableValues = request.getParameter("defaultVariableValues");
		
		PreferencesWrapper preferWapper = new PreferencesWrapper();
		preferWapper.setValue("iframeHeight", iframeHeight);
		preferWapper.setValue("iframeURL", iframeURL);
		preferWapper.setValue("defaultVariableValues", defaultVariableValues);
		PreferencesHelper.savePublicPreferences(request, preferWapper.getPreferences());	
		response.setPortletMode(PortletMode.VIEW);
	}
	@Resource(id="getIframeSrc")
	public void getIframeSrc(ResourceRequest request, ResourceResponse response)
			throws PortletException, IOException {
		String ajaxData = "";
		try {
			PortletPreferences preferences =  PreferencesHelper.getPublicPreference(request);
			String iframeURL = preferences.getValue("iframeURL", null);
			PortletVariableHelper variableHelper = new PortletVariableHelper(request);
			iframeURL = URLDecoder.decode(variableHelper.getRealDataURL(iframeURL),"utf-8");
			String adder = "";
			if (iframeURL.indexOf("?") == -1){
				if (iframeURL.endsWith("?")){
					adder = "";
				}else{
					adder = "?";
				}
			}else{
				if (iframeURL.endsWith("&")){
					adder = "";
				}else{
					adder = "&";
				}
			}
			ajaxData = iframeURL+adder;
		} catch (Exception e) {
			this.logger.error("获取取数据失败getRecordCount", e);
		}
		PrintWriter writer = response.getWriter();
		writer.print(ajaxData);
		writer.close();
	}
}
